import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loginapp/News/NewsPage.dart';
import 'package:loginapp/Main/MainPage.dart';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:simple_animations/simple_animations.dart';
import 'package:supercharged/supercharged.dart';
import 'package:loginapp/Success/NavigationPage.dart';

enum _ColorTween { color1, color2 }


class MainPage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MainPage> {
  OutlineInputBorder outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(30)),
      borderSide: BorderSide(color: Colors.white70, width: 2)); //用于设置表框式样
  OutlineInputBorder focuslineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(30)),
      borderSide: BorderSide(color: Colors.greenAccent, width: 2)); //用于设置表框式样
  TextStyle counttextStyle =
      TextStyle(color: Colors.white, fontSize: 15, height: 0.6);
  bool checked = false;
  RichText? richText;
  String phone = '';
  String errorPhone = '';
  String name = '';
  String errorName = '';
  String errorPassword = '';
  String userpwd = '';
  TextEditingController userpwdController = TextEditingController();
  TextEditingController namecontroller = TextEditingController();
  TextEditingController brithcontroller = TextEditingController();
  TextEditingController phoneController = TextEditingController(); //电话号码
  TextEditingController  controller =  TextEditingController();//验证码
  DateTime initialDate = DateTime.now();
  DateTime firstDate = DateTime(1950, 10, 1);
  DateTime lastDate = DateTime(2035, 10, 1);
  DateTime select = DateTime.now();
  Future brithday(context) async {
    DateTime? b = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: firstDate,
        lastDate: lastDate);
    brithcontroller.text = b.toString().substring(0,10);
  }
  void judgePhone(value) {
    setState(() {
      if (value.length == 11) {
        errorPhone = '手机号验证通过';
      }else
        errorPhone = '手机号格式有误';
    });
  }
  void judgeName(value) {
    setState(() {
      if(value.length <= 1){
        errorName = '姓名至少为2个字符';
      }
      if (value.length <= 5 && value.length>= 2) {
        errorName = '姓名验证通过';
      }
    });
  }
  void judgePwd(value) {
    setState(() {
      if(value.length>=5){
        errorPassword = '密码验证通过';
      }else
      if (value.length < 5) {
        errorPassword = '密码至少为5位';
      }
    });
  }
  void judgeall() {
    String msg = '注册成功';
    String long = '';
    var uname = namecontroller.text;
    var upwd = userpwdController.text;
    var phone = phoneController.text;
    var birth = brithcontroller.text;
    var num = controller.text;
    if (uname.length == 0 || upwd.length < 5||birth.length!=10||phone.length!=11) {
      msg = '请填写完整且合法的注册信息';
    }
    else if(!checked)
      {
        msg = '请勾选同意协议并仔细阅读';
      }
    else if(num.toString()!='1234'){
      msg = '验证码错误，请重新获取';
    }
    if (msg == '注册成功') {
      long = msg+'\n姓名：'+uname+'\n电话:'+phone+'\n生日：'+birth;
    }
    else
      long = msg;

    Fluttertoast.showToast(
        msg: long,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.lightBlueAccent);
    if (msg == '注册成功') {
      Navigator.pushNamed(context, '/main'); //转发实现
    }
  }

  @override
  void initState() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('会员注册'),
        ),
        body:

        //     child: SingleChildScrollView(
        Stack(
           children: <Widget>[
             Positioned.fill(child: AnimatedBackground()),
             onBottom(AnimatedWave(
               height: 180,
               speed: 1.0,
             )),
             onBottom(AnimatedWave(
               height: 120,
               speed: 0.9,
               offset: pi,
             )),
             onBottom(AnimatedWave(
               height: 220,
               speed: 1.2,
               offset: pi / 2,
             )),Positioned.fill(child: AnimatedBackground()),
             onBottom(AnimatedWave(
               height: 180,
               speed: 1.0,
             )),
             onBottom(AnimatedWave(
               height: 120,
               speed: 0.9,
               offset: pi,
             )),
             onBottom(AnimatedWave(
               height: 220,
               speed: 1.2,
               offset: pi / 2,
             )),
             Padding(padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
               //child: SingleChildScrollView(
               child: Column(
                 children: <Widget>[

                   Text(
                     //主标题容器内容及其式样设置
                     "账号注册",
                     style: TextStyle(
                         color: Colors.white,
                         fontSize: 23,
                         fontWeight: FontWeight.bold,
                         height: 5),
                   ),
                   TextField(
                     //第一个表单组件
                     controller: phoneController,
                     onChanged: (value) {
                       phone = value;
                       //调用判断手机号长度
                       judgePhone(value);
                     },
                     keyboardType: TextInputType.number, //手机输入
                     maxLength: 11,
                     decoration: InputDecoration(
                       counterText: errorPhone,
                       counterStyle: counttextStyle, //Text式样 红色，15字号
                       prefixIcon: Icon(Icons.phone_android),
                       labelText: '请输入手机号', //
                       labelStyle: counttextStyle,// 表框内的提示信息
                       hasFloatingPlaceholder: false, hintText: '手机号',
                       hintStyle: counttextStyle,
                       contentPadding: EdgeInsets.symmetric(vertical: 10), //垂直方向边距
                       enabledBorder: outlineInputBorder,
                       focusedBorder: focuslineInputBorder,
                     ),
                   ),
                   TextField(
                     //keyboardType: TextInputType.name, //姓名输入
                       controller: namecontroller,
                       onChanged: (value) {
                         name = value;
                         //调用判断手机号长度
                         judgeName(value);
                       },
                       maxLength: 5,
                       decoration: InputDecoration(
                         counterText: errorName,
                         counterStyle: counttextStyle, //Text式样 红色，15字号
                         prefixIcon: Icon(Icons.perm_identity_sharp),
                         labelText: '请输入姓名',
                         labelStyle: counttextStyle,//表框内的提示信息
                         hasFloatingPlaceholder: false, hintText: '姓名',
                         hintStyle: counttextStyle,//表框内的提示信息
                         contentPadding: EdgeInsets.symmetric(vertical: 1),
                         enabledBorder: outlineInputBorder,
                         focusedBorder: focuslineInputBorder,
                       )),
                   TextField(
                       obscureText: true,
                       controller: userpwdController,
                       onChanged: (value) {
                         userpwd = value;
                         //调用判断密码长度
                         judgePwd(value);
                       },
                       maxLength: 8,
                       decoration: InputDecoration(
                         counterText: errorPassword,
                         counterStyle: counttextStyle, //Text式样 红色，15字号
                         prefixIcon: Icon(Icons.lock_open),
                         labelText: '请输入密码',
                         labelStyle: counttextStyle,//表框内的提示信息
                         hasFloatingPlaceholder: false, hintText: '密码',
                         hintStyle: counttextStyle,//表框内的提示信息
                         contentPadding: EdgeInsets.symmetric(vertical: 1),
                         enabledBorder: outlineInputBorder,
                         focusedBorder: focuslineInputBorder,
                       )),
                   TextField(
                     controller: brithcontroller,
                     maxLength: 10,
                     decoration: InputDecoration(
                       //counterText: "出僧日期不超过十个字符",
                       counterStyle: TextStyle(
                           color: Colors.white, fontSize: 15), //Text式样 红色，15字号
                       prefixIcon: Icon(Icons.cake),
                       labelText: '请输入出生日期', //
                       labelStyle:  TextStyle(color: Colors.white, fontSize: 15),// 表框内的提示信息
                       hasFloatingPlaceholder: false, hintText: '出生日期',
                       hintStyle:  TextStyle(color: Colors.white, fontSize: 15),//表框内的提示信息
                       contentPadding: EdgeInsets.symmetric(vertical: 1),
                       enabledBorder: outlineInputBorder,
                       focusedBorder: focuslineInputBorder,
                     ),
                     onTap: (){brithday(context);},
                   ),
                   TextField(
                       controller: controller,
                       decoration: InputDecoration(
                         // counterText: "验证码",
                         // counterStyle:
                         // TextStyle(color: Colors.red, fontSize: 15), //Text式样 红色，15字号

                           prefixIcon: Icon(Icons.settings_overscan),
                           labelText: '请输入验证码', //表框内的提示信息
                           labelStyle: counttextStyle,
                           contentPadding: EdgeInsets.symmetric(vertical: 1),
                           enabledBorder: outlineInputBorder,
                           focusedBorder: focuslineInputBorder,
                           suffixIcon: OutlineButton(
                             // borderSide: BorderSide(color: Colors.red, width: 2),
                             child: Text('获取验证码',style: TextStyle(color: Colors.white),),
                             onPressed: () {
                               print('验证码：1234');
                             },
                           ))),
                   CheckboxListTile(
                     value: checked,
                     title: Text(
                       '同意',
                       style: TextStyle(color: Colors.redAccent,fontSize: 20),
                     ),
                     subtitle: Text(
                       "同意表示宁以及阅读该协议",
                       style: TextStyle(color: Colors.amberAccent),
                     ),
                     secondary: Icon(Icons.info),
                     controlAffinity: ListTileControlAffinity.leading,
                     activeColor: Colors.amber,
                     onChanged: (value) {
                       setState(() {
                         checked = value!;
                         if (checked) {
                           richText = RichText(
                             textAlign: TextAlign.center,
                             text: TextSpan(
                                 text: '协议内容:\n',
                                 style: TextStyle(color: Colors.red),
                                 children: [
                                   TextSpan(
                                       text: '富强、民主、文明\n和谐、自由、平等\n公正、法治、爱国\n敬业、诚信、友善',
                                       style: TextStyle(color: Colors.white))
                                 ]),
                           );
                         } else {
                           richText = null;
                         }
                       });
                     },
                   ),

                   FlatButton(
                     color: Colors.tealAccent,
                     child:
                     Container(alignment: Alignment.center, child: Text('注册')),
                     onPressed: () {
                       //Navigator.pushNamed(context, '/main');
                       judgeall();
                     },
                   ),
                   Container(
                     child: richText,
                   )
                 ],
               ),)

             //)
           ],
         ),
        resizeToAvoidBottomInset: false,//防止键盘调用定格溢出
        );
  }

}
/*以下为背景页面控制*/
onBottom(Widget child) => Positioned.fill(
  child: Align(
    alignment: Alignment.bottomCenter,
    child: child,
  ),
);

class AnimatedWave extends StatelessWidget {
  final double? height;
  final double? speed;
  final double offset;

  AnimatedWave({this.height, this.speed, this.offset = 0.0});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      return Container(
        height: height,
        width: constraints.biggest.width,
        child: LoopAnimation<double>(
            duration: (5000 / speed!).round().milliseconds,
            tween: 0.0.tweenTo(2 * pi),
            builder: (context, child, value) {
              return CustomPaint(
                foregroundPainter: CurvePainter(value + offset),
              );
            }),
      );
    });
  }
}

class CurvePainter extends CustomPainter {
  final double value;

  CurvePainter(this.value);

  @override
  void paint(Canvas canvas, Size size) {
    final white = Paint()..color = Colors.white.withAlpha(60);
    final path = Path();

    final y1 = sin(value);
    final y2 = sin(value + pi / 2);
    final y3 = sin(value + pi);

    final startPointY = size.height * (0.5 + 0.4 * y1);
    final controlPointY = size.height * (0.5 + 0.4 * y2);
    final endPointY = size.height * (0.5 + 0.4 * y3);

    path.moveTo(size.width * 0, startPointY);
    path.quadraticBezierTo(
        size.width * 0.5, controlPointY, size.width, endPointY);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();
    canvas.drawPath(path, white);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

class AnimatedBackground extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final tween = MultiTween<_ColorTween>()
      ..add(
        _ColorTween.color1,
        Color(0xffD38312).tweenTo(Colors.lightBlue.shade900),
        3.seconds,
      )
      ..add(
        _ColorTween.color2,
        Color(0xff32A842FF).tweenTo(Colors.lightBlueAccent),
        3.seconds,
      );

    return MirrorAnimation<MultiTweenValues<_ColorTween>>(
      tween: tween,
      duration: tween.duration,
      builder: (context, child, value) {
        return Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    value.get<Color>(_ColorTween.color1),
                    value.get<Color>(_ColorTween.color2)
                  ])),
        );
      },
    );
  }
}

